/*
 * marketsim-eclipsetrader
 *
 * Copyright (C) 2008-2011 Steve Phelps and John Cartlidge
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of
 * the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 */
/*
 *  (C) Victria Ltd. 2007
 */
package victria.marketsim.eclipsetrader;


import org.apache.log4j.Logger;
import org.springframework.remoting.RemoteAccessException;

import victria.marketsim.core.MarketService;
import victria.marketsim.core.MarketState;
import victria.marketsim.eclipsetrader.event.MarketModelChangedEvent;
import victria.marketsim.eclipsetrader.event.MarketModelClockEvent;
import victria.marketsim.eclipsetrader.event.VisualisationEvent;
import victria.marketsim.eclipsetrader.event.VisualisationEventListener;

/**
 * A model of the entire market state. Any GUI component providing a market
 * related view should listen on this model.
 * 
 * The model is updated in response to MarketModelClockEvent events. When a
 * clock event is received the model fetches a copy of the entire market state
 * from the server and holds a copy on the client.
 * 
 * @author john
 * 
 */
public class MarketStateController extends AbstractController implements
		VisualisationEventListener {

	/**
	 * The current snapshot of the entire market state.
	 */
	protected MarketState marketState;
	
	protected MarketService marketService; 
	
	static Logger logger = Logger.getLogger(MarketStateController.class);
	
	public MarketStateController() {
		marketState = new MarketState();
	}
	
	public void eventOccurred(VisualisationEvent e) {
		
		logger.debug("Received " + e);		
		
//		if (e instanceof OrderSentEvent) {
//			refreshState();
//			fireEvent(new MarketModelChangedEvent(this));
//		}
//		
		if (e instanceof MarketModelClockEvent) {
			refreshState();
			fireEvent(new MarketModelChangedEvent(this));
		}
	}
	

	public void copyMarketStateFromServer() {
		logger.debug("Copying marketState from server..");
		marketState = marketService.getMarketState();
		logger.debug("done.");
		logger.debug("marketState = " + marketState);
	}
			

	/** Refresh orders with all orders in the marketplace
	 *  that are in the opposite direction of 
	 *  currentOrderPosition
	 */
	protected synchronized void refreshState() {		
		try {
			copyMarketStateFromServer();
		} catch (RemoteAccessException e) {
			logger.error(e);
		}
	}
	
	public MarketState getMarketState() {
		return marketState;
	}


	public MarketService getMarketService() {
		return marketService;
	}

	public void setMarketService(MarketService marketService) {
		this.marketService = marketService;
	}
	
	
}
